package com.learn.setget;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author chenxin
 * @time 2016-12-16-10:21
 */
public class FutureTest {
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2, 10, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(8), new DefaultThreadFactory());
        Future<Integer> task = poolExecutor.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                try {
                    Thread.sleep(1000);
                System.out.println("task run");
                    return 5 / 0;
                }
                catch (Exception e){
                    System.out.println("callable e");
                    e.printStackTrace();
                }
                return 1;
            }
        });

//        try {
//            Integer ret = task.get();
//            System.out.println(ret);
//        } catch (Exception e){
//            System.out.println("get exception");
//            e.printStackTrace();
//
//            System.out.println("#cause#");
//            System.out.println(e.getCause());
//        }

        Thread.sleep(5000);
        System.out.println("end");

//        poolExecutor.execute(() -> System.out.println(3/0));
    }


    /**
     * The default thread factory
     */
    static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = "pool-my-" +
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }
}
